package ru.dc.gui.swing;

import ru.dc.object.ServerInfo;

import javax.swing.table.AbstractTableModel;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <pre>
 * User: Penkov Vladimir
 * Date: 02.11.2010
 * Time: 14:16:03
 * </pre>
 */
public class HubFilterTableModel extends AbstractTableModel{

    private List<ServerInfo> hubs = new ArrayList<ServerInfo>();
    private Map<ServerInfo, Boolean> selection = new HashMap<ServerInfo, Boolean>();

    public int getRowCount() {
        return hubs.size();
    }

    public int getColumnCount() {
        return 2;
    }

    public Object getValueAt(int rowIndex, int columnIndex) {
        switch (columnIndex) {
            case 0 : return selection.get(hubs.get(rowIndex));
            case 1 : return hubs.get(rowIndex);
        }
        return null;
    }

    @Override
    public Class<?> getColumnClass(int columnIndex) {
        switch (columnIndex) {
            case 0 : return Boolean.class;
            case 1 : return ServerInfo.class;
        }
        return super.getColumnClass(columnIndex);
    }

    @Override
    public boolean isCellEditable(int rowIndex, int columnIndex) {
        return columnIndex==0;
    }

    public void addHub(ServerInfo hub) {
        hubs.add(hub);
        selection.put(hub, true);
        fireTableRowsInserted(hubs.size()-1, hubs.size()-1);

    }

    @Override
    public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
        switch (columnIndex) {
            case 0 :
                Boolean b = (Boolean) aValue;
                selection.put(hubs.get(rowIndex), b);
                fireTableCellUpdated(rowIndex, columnIndex);
                break;

        }
    }

    public List<ServerInfo> getSelected() {
        List<ServerInfo> res = new ArrayList<ServerInfo>();
        for (ServerInfo info : hubs) {
            if (selection.get(info)) {
                res.add(info);
            }
        }
        return res;
    }
}
